<?php

namespace app\api\controller;

use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\response\Json;
/**
 * 文章分类
 *
 * admin-ArticleClass
 *
 * @Apidoc\Title("文章分类")
 * @Apidoc\Group("api")
 */
class ArticleClass extends Auth
{

    /**
     * list
     * @Apidoc\Title("获取文章分类")
     */
    public function list(): \think\response\Json
    {
        $res = \app\common\model\ArticleClass::where('member_id', $this->request->uid)->order('sort asc,id asc')->select();
        foreach($res as $key=>$v){
            $res[$key]["count"]= \app\common\model\Article::where([
                "article_class_id"=>$v['id'],
                'state'=>2,
            ])->count();
        }
        return success('ok', $res);
    }

    /**
     * @Apidoc\Title("新增")
     * @Param("name", type="varchar" ,desc="分类名称",require=true)
     * @Param("order", type="int", desc="排序",)
     * @Apidoc\Method("post")
     */
    public function add()
    {
        $data = request()->post(['name', 'sort']);
        validate([
            'name|分类名称' => 'require',
        ])->check($data);
        $data['member_id'] = $this->request->uid;
        \app\common\model\ArticleClass::create($data);
        return success();
    }

    /**
     * delete
     * @Apidoc\Method("post")
     * @Param("id", type="int", desc="id",require=true)
     * @Apidoc\Title("删除")
     */
    public function delete()
    {
        $id = input('id');
        $article_class = \app\common\model\ArticleClass::find($id);
        if($article_class['member_id'] != $this->request->uid){
            return error('非法请求');
        }
        \app\common\model\ArticleClass::destroy($id);
        return success();
    }


    /**
     * update
     * @Apidoc\Title("修改")
     * @Param("name", type="varchar" ,desc="分类名称",require=true)
     * @Param("id", type="int", desc="id",require=true)
     * @Param("order", type="int", desc="排序")
     * @Apidoc\Method("post")
     */
    public function update()
    {
        $data = request()->post(['id', 'name', 'sort']);
        validate([
            'name|分类名称' => 'require',
            'id|分类id' => 'require',
        ])->check($data);

        $article_class = \app\common\model\ArticleClass::find($data['id']);
        if($article_class['member_id'] != $this->request->uid){
            return error('非法请求');
        }

        \app\common\model\ArticleClass::update($data);
        return success($data);
    }
}
